import { Injectable } from '@nestjs/common';
import { RoleDto, RoleUpdateDto, QueryRoleDto } from './dto/role.dto';
import { MongodbService } from '../../database/mongodb/mongodb.service';
import { BusinessException } from '../../types/exception/business.exception';
import { ERR_MSG } from '../../types/errcode';
import * as _ from 'lodash';
import { v4 as uuidv4 } from 'uuid';

@Injectable()
export class RoleService {
  constructor(private readonly _mongodbService: MongodbService) {}

  // 获取角色列表
  async getRoleList(req, query: QueryRoleDto) {
    const { skip, limit } = req.herin;

    const match = {
      $and: [
        query.roleName
          ? {
              roleName: {
                $regex: `${query.roleName}`,
                $options: 'i',
              },
            }
          : {},
      ],
    };

    const list = await this._mongodbService.RoleModel.aggregate([
      {
        $match: match,
      },
      { $skip: skip ? skip : 0 },
      { $limit: limit ? limit : 10 },
      { $project: { _id: 0, __v: 0 } },
    ]);

    const total = await this._mongodbService.RoleModel.find(match).countDocuments();

    return { list, total };
  }

  // 获取角色信息
  async getRoleInfo(id: string) {
    // 查询角色信息
    const info = await this._mongodbService.RoleModel.findOne({ id })
      .select({ _id: 0, __v: 0, createdAt: 0, updatedAt: 0 }) // 排除不需要的字段
      .lean()
      .exec();

    if (!info) {
      throw new BusinessException(ERR_MSG.ROLE_NOT_EXIST);
    }

    return { info };
  }

  // 新增角色
  async addRole(req, body: RoleDto) {
    // 校验当前角色是否存在
    const checkRoleName = await this._mongodbService.RoleModel.findOne({
      roleName: body.roleName,
    });
    if (!_.isEmpty(checkRoleName)) {
      throw new BusinessException(ERR_MSG.ROLE_IS_EXIST);
    }

    // 添加角色对应的权限，保存权限code和对应的中文 --TODO

    // 存储
    const returnData = await this._mongodbService.RoleModel.create({
      // id
      id: uuidv4().replace(/-/g, ''),

      // 角色
      roleName: body.roleName,
    });

    return { msg: returnData.roleName + '-角色创建成功' };
  }

  // 更新角色
  async updateRole(req, body: RoleUpdateDto) {
    const { id, ...updateData } = body;

    // 判断是否存在
    const role = await this._mongodbService.RoleModel.findOne({
      id: id,
    });
    if (_.isEmpty(role)) {
      throw new BusinessException(ERR_MSG.ROLE_NOT_EXIST);
    }

    // 判断是否重名
    if (role.roleName !== updateData.roleName) {
      const checkRoleName = await this._mongodbService.RoleModel.findOne({
        roleName: updateData.roleName,
      });
      if (!_.isEmpty(checkRoleName)) {
        throw new BusinessException(ERR_MSG.ROLE_IS_EXIST);
      }
    }

    // 添加角色对应的权限，保存权限code和对应的中文 --TODO

    const res = await this._mongodbService.RoleModel.updateOne({ id: id }, { $set: updateData });
    if (res.modifiedCount > 0) {
      return { msg: '更新成功' };
    } else {
      return { msg: '更新成功' };
    }
  }

  // 删除角色
  async deleteRole(req, body: any) {
    const { ids } = body;

    if (ids.length <= 0) {
      throw new BusinessException({
        msg: '请提供要删除的项',
        code: '10001',
      });
    }

    // 判断ids是否存在
    const role = await this._mongodbService.RoleModel.find({
      id: { $in: ids },
    });
    if (_.isEmpty(role)) {
      throw new BusinessException(ERR_MSG.ROLE_NOT_EXIST);
    }

    // 检查当前角色是否有用户关联 --TODO

    const delInfo = await this._mongodbService.RoleModel.deleteMany({
      id: { $in: ids },
    });

    return { msg: true, delInfo };
  }
}
